//
//  ZKPopWindowMenuView.m
//  朱凯的工具箱
//
//  Created by pro on 17/2/6.
//  Copyright © 2017年 zhukai. All rights reserved.
//

#import "ZKPopWindowMenuView.h"

#define KAnimationDuration 0.25
#define KMaxTableLines 3

static CGFloat kSingleMenuHeight = 40;
static CGFloat kLayerCornor = 5;
static CGFloat kArrowLeastMargin = 5;
static CGFloat kArrowWidth = 13;
static CGFloat kArrowHeight = 10;

typedef enum : NSUInteger {
    ZKMenuArrowDirectionUp,
    ZKMenuArrowDirectionDown,
} ZKMenuArrowDirectionType;

#pragma mark - 内容视图tableview的单元格

@interface ZKPopWindowMenuCell ()
@property (nonatomic, strong) UIImageView   *iconView;
@property (nonatomic, strong) UILabel       *titleLabel;
@property (nonatomic, strong) UILabel       *line;

@end

@implementation ZKPopWindowMenuCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupUI];
    }
    return self;
}
- (void)setupUI {
    
    _iconView = [[UIImageView alloc] init];
    [self.contentView addSubview:_iconView];
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.adjustsFontSizeToFitWidth = YES;
    _titleLabel.font = FONT(16);
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    _titleLabel.textColor = [UIColor colorWithWhite:0.8 alpha:1];
    [self.contentView addSubview:_titleLabel];
    
    _line = [[UILabel alloc] init];
    _line.backgroundColor = BY_LINE_COLOR;
    [self.contentView addSubview:_line];
}


- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    _iconView.frame = CGRectMake(0, 0, self.height * 0.5, self.height * 0.5);
    _iconView.y = self.height / 2;
    _iconView.left = _iconView.top;
    if (!_iconView.image) {
        _titleLabel.frame = CGRectMake(_iconView.left, 0, self.width - (_iconView.right + _iconView.left), self.height);

    } else {
        _titleLabel.frame = CGRectMake(_iconView.right + _iconView.left, 0, self.width - (_iconView.right + _iconView.left), self.height);

    }
    
    
    _line.frame = CGRectMake(10, self.height - 0.5, self.width - 20, 0.5);
}

@end


#pragma mark - 内容视图，用于绘制和填充数据
@implementation ZKPopWindowMenuContentView
{
    // 数据
    NSArray                     *_titles;       // 标题
    NSArray                     *_imageNames;   // 图片
    CGPoint                     _arrowPoint;    // 箭头尖点
    ZKMenuArrowDirectionType    _dir;           // 箭头方向
    ZKDoneBlock                 _doneBlock;     // 选中回调
    
    // UI
    CAShapeLayer                *_backgroundLayer;
    UITableView                 *_table;
}
- (instancetype)initWithFrame:(CGRect)frame
                   arrowPoint:(CGPoint)arrowPoint
                     arrowDir:(ZKMenuArrowDirectionType)dirType
                       titles:(NSArray *)titles
                   imageNames:(NSArray *)imageNames
                    doneBlock:(ZKDoneBlock)doneBlock {
    
    if (self = [super initWithFrame:frame]) {

        _arrowPoint = arrowPoint;
        _dir = dirType;
        _titles = titles;
        _imageNames = imageNames;
        _doneBlock = doneBlock;
        
        [self setupBackgroudLayer];
        [self setupTable];
    }
    return self;
}
- (void)setupBackgroudLayer {
    
    _backgroundLayer = [CAShapeLayer layer];
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:_arrowPoint];
    // 箭头朝上，顺时针添加路径
    if (_dir == ZKMenuArrowDirectionUp) {
        [path addLineToPoint:CGPointMake(_arrowPoint.x + kArrowWidth / 2, _arrowPoint.y + kArrowHeight)];
        [path addLineToPoint:CGPointMake(self.width - kLayerCornor, _arrowPoint.y + kArrowHeight)];
        [path addArcWithCenter:CGPointMake(self.width - kLayerCornor, _arrowPoint.y + kArrowHeight + kLayerCornor) radius:kLayerCornor startAngle:-M_PI / 2 endAngle:0 clockwise:YES];
        [path addLineToPoint:CGPointMake(self.width, _arrowPoint.y + kArrowHeight + kLayerCornor)];
        [path addLineToPoint:CGPointMake(self.width, self.height - kLayerCornor)];
        [path addArcWithCenter:CGPointMake(self.width - kLayerCornor, self.height - kLayerCornor) radius:kLayerCornor startAngle:0 endAngle:M_PI / 2 clockwise:YES];
        [path addLineToPoint:CGPointMake(self.width - kLayerCornor, self.height)];
        [path addLineToPoint:CGPointMake(kLayerCornor, self.height)];
        [path addArcWithCenter:CGPointMake(kLayerCornor, self.height - kLayerCornor) radius:kLayerCornor startAngle:M_PI / 2 endAngle:M_PI clockwise:YES];
        [path addLineToPoint:CGPointMake(0, self.height - kLayerCornor)];
        [path addLineToPoint:CGPointMake(0, _arrowPoint.y + kArrowHeight + kLayerCornor)];
        [path addArcWithCenter:CGPointMake(kLayerCornor, _arrowPoint.y + kArrowHeight + kLayerCornor) radius:kLayerCornor startAngle:M_PI endAngle:M_PI / 2 * 3 clockwise:YES];
        [path addLineToPoint:CGPointMake(kLayerCornor, _arrowPoint.y + kArrowHeight)];
        [path addLineToPoint:CGPointMake(_arrowPoint.x - kArrowWidth / 2, _arrowPoint.y + kArrowHeight)];
        [path closePath];
    }
    // 箭头朝下，顺时针添加路径
    else {
        [path addLineToPoint:CGPointMake(_arrowPoint.x - kArrowWidth / 2, _arrowPoint.y - kArrowHeight)];
        [path addLineToPoint:CGPointMake(kLayerCornor, _arrowPoint.y - kArrowHeight)];
        [path addArcWithCenter:CGPointMake(kLayerCornor, _arrowPoint.y - kArrowHeight - kLayerCornor) radius:kLayerCornor startAngle:M_PI / 2 endAngle:M_PI clockwise:YES];
        [path addLineToPoint:CGPointMake(0, _arrowPoint.y - kArrowHeight - kLayerCornor)];
        [path addLineToPoint:CGPointMake(0, kLayerCornor)];
        [path addArcWithCenter:CGPointMake(kLayerCornor, kLayerCornor) radius:kLayerCornor startAngle:M_PI endAngle:M_PI / 2 * 3 clockwise:YES];
        [path addLineToPoint:CGPointMake(kLayerCornor, 0)];
        [path addLineToPoint:CGPointMake(self.width - kLayerCornor, 0)];
        [path addArcWithCenter:CGPointMake(self.width - kLayerCornor, kLayerCornor) radius:kLayerCornor startAngle:M_PI / 2 * 3 endAngle:M_PI * 2 clockwise:YES];
        [path addLineToPoint:CGPointMake(self.width, kArrowHeight)];
        [path addLineToPoint:CGPointMake(self.width, _arrowPoint.y - kArrowHeight - kLayerCornor)];
        [path addArcWithCenter:CGPointMake(self.width - kLayerCornor, _arrowPoint.y - kArrowHeight - kLayerCornor) radius:kLayerCornor startAngle:0 endAngle:M_PI / 2 clockwise:YES];
        [path addLineToPoint:CGPointMake(self.width - kLayerCornor, _arrowPoint.y - kArrowHeight)];
        [path addLineToPoint:CGPointMake(_arrowPoint.x + kArrowWidth / 2, _arrowPoint.y - kArrowHeight)];
        [path closePath];
    }
    
    _backgroundLayer.path = path.CGPath;
    _backgroundLayer.fillColor = rgba(38, 38, 38, 1).CGColor;
    
    [self.layer addSublayer:_backgroundLayer];
}

// 创建表视图
- (void)setupTable {
    
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, _dir == ZKMenuArrowDirectionUp ? kArrowHeight : 0, self.width, self.height - kArrowHeight) style:UITableViewStylePlain];
    _table.backgroundColor = [UIColor clearColor];
    _table.delegate = self;
    _table.dataSource = self;
    [self addSubview:_table];
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
}
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return MAX(_titles.count, _imageNames.count);
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZKPopWindowMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[ZKPopWindowMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.backgroundColor = [UIColor clearColor];
    }
    if (_titles) {
        cell.titleLabel.text = _titles[indexPath.row];
    }
    if (_imageNames) {
        cell.iconView.image = [UIImage imageNamed:_imageNames[indexPath.row]];
    } else {
        cell.titleLabel.left = 10;
    }
    
    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kSingleMenuHeight;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_doneBlock) {
        _doneBlock(indexPath.row);
    }
}


@end

#pragma mark - 主视图，用于显示和控制内容视图
@implementation ZKPopWindowMenuView
{
    ZKDismissBlock  _dismissBlock;  // 取消回调
}


+ (instancetype)showInWindowWithPoint:(CGPoint)point
                            menuWidth:(CGFloat)menuWidth
                               titles:(NSArray *)titles
                           imageNames:(NSArray *)imageNames
                            doneBlock:(ZKDoneBlock)doneBlock
                         dismissBlock:(ZKDismissBlock)dismissBlock {
    
    // 创建背景
    ZKPopWindowMenuView *bgView = [[ZKPopWindowMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    bgView.backgroundColor = [UIColor clearColor];
    bgView->_dismissBlock = dismissBlock;
    [bgView addTarget:bgView action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    
    // 创建内容视图的位置和尺寸信息，并计算箭头尖点的位置
    CGFloat x, y, width, height, arrowX, arrowY;
    ZKMenuArrowDirectionType dir;
    CGFloat margin = 5;
    // 设置width
    width = menuWidth;
    // 设置height，菜单视图最多显示三行，其余的需要滑动才能看见
    height = kSingleMenuHeight * MIN(MAX(titles.count, imageNames.count), KMaxTableLines) + kArrowHeight;
    // 设置x
    if (point.x + menuWidth / 2 > SCREEN_WIDTH - margin) {
        x = SCREEN_WIDTH - margin - menuWidth;
        arrowX = width / 2 + (point.x + menuWidth / 2 - (SCREEN_WIDTH - margin));
        arrowX = MIN(arrowX, width - kArrowLeastMargin - kArrowWidth / 2);
    } else if (point.x - menuWidth / 2 < margin) {
        x = margin;
        arrowX = point.x - margin;
        arrowX = MAX(arrowX, kArrowLeastMargin + kArrowWidth / 2);
    } else {
        x = point.x - menuWidth / 2;
        arrowX = width / 2;
    }
    // 设置y
    if (point.y < SCREEN_HEIGHT / 2) {
        y = point.y + margin;
        arrowY = 0;
        dir = ZKMenuArrowDirectionUp;
    } else {
        y = point.y - margin - height;
        arrowY = height;
        dir = ZKMenuArrowDirectionDown;
    }
    ZKPopWindowMenuContentView *contentView = [[ZKPopWindowMenuContentView alloc] initWithFrame:CGRectMake(x, y, width, height) arrowPoint:CGPointMake(arrowX, arrowY)  arrowDir:dir titles:titles imageNames:imageNames doneBlock:doneBlock];
    [bgView addSubview:contentView];
    
    // 把所有视图添加到窗口上
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:bgView];
    
    bgView.alpha = 0;
    [UIView animateWithDuration:KAnimationDuration animations:^{
        bgView.alpha = 1;
    }];
    
    return bgView;
}


#pragma mark - 点击事件
- (void)dismiss {
    
    if (_dismissBlock) {
        _dismissBlock();
    }
    
    [UIView animateWithDuration:KAnimationDuration animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
